<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Upload extends Controller
{
    // todo: add to config file
    private $preview_width = 150;
    private $preview_height = 200;
    private $upload_dir = 'img/upload';
    private $file_prefix = 'pr_';

    public function action_index()
    {
        $this->response->body(View::factory('upload')->set('msgs', NULL));
    }

    public function action_save()
    {
        if ($this->request->method() != HTTP_Request::POST) {
            Request::current()->redirect('home');
        }

        $fileRules = Validation::factory(array_merge($_POST, $_FILES));

        $fileRules->rule('file', 'Upload::not_empty');
        $fileRules->rule('file', 'Upload::valid');
        $fileRules->rule('file', 'Upload::type', array(':value', array('jpg', 'png')));

        //$fileRules->rule('description', 'not_empty');
        $fileRules->rule('description', 'max_length', array(':value', 50));

        if ($fileRules->check()) {
            // Custom ex.handler must be impl
            $fileName = Upload::save($_FILES['file'], NULL, $this->upload_dir);
            if (!$fileName)
                throw new Kohana_Exception('Error: file name');
            $file = Controller_Upload::getFileName($fileName);
            $this->savePreviewImage($file);
            $this->saveModel($file);
            $msg = array('ok' => 'File uploaded succeful.');
        } else {
            $msg = $fileRules->errors('file_val');
        }

        //
        $this->response->body(View::factory('upload')->set('msgs', $msg));
    }

    private function savePreviewImage($filename)
    {
        $file = DOCROOT . $this->upload_dir . '/' . $filename;

        list($orig_width, $orig_height) = getimagesize($file);
        $orig_ratio = $orig_width / $orig_height;
        $img_ratio = $this->preview_width / $this->preview_height;
        $image = Image::factory($file);
        if ($orig_ratio >= $img_ratio) {
            $image->resize(NULL, $this->preview_height);
            $image->crop($this->preview_width, $this->preview_height);
        } else {
            $image->resize($this->preview_width, NULL);
            $image->crop($this->preview_width, $this->preview_height);
        }

        $image->save($this->upload_dir . '/' . $this->file_prefix . $filename);
    }

    private function saveModel($filename)
    {
        $img = ORM::factory('image');
        $img->img_name = $filename;
        $img->description = Arr::get($_POST, 'description', '');
        $img->save();
    }

    private static function getFileName($filename)
    {
        $pathParts = pathinfo($filename);
        return $pathParts['basename'];
    }
}
